package com.myblog.listener;

import com.myblog.pojo.CustomContext;
import com.myblog.pojo.CustomDataSource;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class DataSourceListener implements ServletContextListener {

    private ZkClient zkClient;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("contextInitialized ...");
        try {
            zkClient = new ZkClient("127.0.0.1:2181");

            zkClient.subscribeDataChanges("/datasource", new IZkDataListener() {

                @Override
                public void handleDataChange(String dataPath, Object data) throws Exception {
                    String datasourceStr = data.toString();

                    String username = datasourceStr.split("-")[0];
                    String password = datasourceStr.split("-")[1];
                    String url = datasourceStr.split("-")[2];

                    CustomDataSource dataSource = (CustomDataSource) CustomContext.getBean("dataSource");
                    System.out.println("修改前：用户名:"+dataSource.getUsername()+" 密码:"+dataSource.getPassword()+" 数据库连接:"+dataSource.getUrl());
                    dataSource.setUsername(username);
                    dataSource.setPassword(password);
                    dataSource.setUrl(url);
                    System.out.println("修改后：用户名:"+dataSource.getUsername()+" 密码:"+dataSource.getPassword()+" 数据库连接:"+dataSource.getUrl());
                    dataSource.refresh();
                    System.out.println("完成连接池刷新");
                }

                @Override
                public void handleDataDeleted(String dataPath) throws Exception {

                }
            });
        } catch (Exception e) {
            if (zkClient != null) {
                zkClient.close();
            }
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        zkClient.close();
    }
}
